<?php

namespace app\controllers;

use app\common\utils\QyWechat;
use app\models\GkyQyhDepartment;
use app\models\GkyQyhDeptUser;
use Yii;
use app\models\GkyQyhUser;
use app\models\GkyQyhUserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * GkyQyhUserController implements the CRUD actions for GkyQyhUser model.
 */
class GkyQyhUserController extends Controller
{
    public $layout='main_1';
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all GkyQyhUser models.
     * @return mixed
     */
    public function actionIndex($isUpdata = false)
    {
        if($isUpdata){
            GkyQyhUser::updataByAll();
        }

        $searchModel = new GkyQyhUserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single GkyQyhUser model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new GkyQyhUser model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new GkyQyhUser();

        if ($model->load(Yii::$app->request->post())) {

            //保存图片地址
            $files = Yii::$app->request->post('files');
//            $fileNames = Yii::$app->request->post('fileNames');
            $fileStatus = Yii::$app->request->post('fileStatus');
            for($i = 0 ; $i < count($fileStatus);$i++){
                if($fileStatus[$i] == 1){
                    $model->signature = $files[$i];
                }

            }

            $qyh = $model->qyh;

            $departments = Yii::$app->request->post('departments');
            $departmentList = [];
            foreach($departments as $department){
                $dept = [];
                $dept['dept_id'] = $department;
                $dept['user_id'] = $model->userid;
                $departmentList[] = $dept;
            }
            GkyQyhDeptUser::saveList($qyh->corpid,$departmentList);

            $options = array(
                'token'=>'gky',
                'encodingaeskey'=>$qyh->aeskey,
                'appid'=>$qyh->corpid,
                'appsecret'=>$qyh->secret,
            );
            $department = [];
            foreach($departments as $deptid){
                $dept = GkyQyhDepartment::findOne($deptid);
                $department[] = $dept->dno;
            }
            $weObj = new QyWechat($options);
            $data = array(
                "userid" => $model->userid,
                "name" => $model->name,
                "department" => $department,
                "position" => $model->position,
                "mobile" => $model->mobile,
                "gender" => $model->gender,
                "weixinid" => $model->weixinid
            );
            $result = $weObj->createUser($data);

            if($result['errcode'] == 0){
                if($model->save()){
                    return $this->redirect(['view', 'id' => $model->id]);
                }else{
                    return $this->render('create', [
                        'model' => $model,
                    ]);
                }
            }else{
                return $this->render('create', [
                    'model' => $model,
                ]);
            }

        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing GkyQyhUser model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

             //保存图片地址
            $files = Yii::$app->request->post('files');
            $fileStatus = Yii::$app->request->post('fileStatus');
            for($i = 0 ; $i < count($fileStatus);$i++){
                if($fileStatus[$i] == 1){
                    $model->signature = $files[$i];
                    $model->save();
                }

            }
            
            //��ȡ��ǰ��ҵ��
            $qyh = $model->qyh;

            $departments = Yii::$app->request->post('departments');
            $departmentList = [];
            foreach($departments as $department){
                $dept = [];
                $dept['dept_id'] = $department;
                $dept['user_id'] = $model->userid;
                $departmentList[] = $dept;
            }
            GkyQyhDeptUser::saveList($qyh->corpid,$departmentList);

            $options = array(
                'token'=>'gky',   //��дӦ�ýӿڵ�Token
                'encodingaeskey'=>$qyh->aeskey,//��д�����õ�EncodingAESKey
                'appid'=>$qyh->corpid,  //��д�߼����ù��ܵ�appid
                'appsecret'=>$qyh->secret, //��д�߼����ù��ܵ���Կ
            );
            $department = [];
            foreach($departments as $deptid){
                $dept = GkyQyhDepartment::findOne($deptid);
                $department[] = $dept->dno;
            }
            $weObj = new QyWechat($options);
            $data = array(
                 "userid" => $model->userid,
                 "name" => $model->name,
                 "department" => $department,
                 "position" => $model->position,
                 "mobile" => $model->mobile,
                 "gender" => $model->gender,     //�Ա�gender=0��ʾ�У�=1��ʾŮ
                 "weixinid" => $model->weixinid
             );
            $result = $weObj->updateUser($data);

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'deptUsers' => $model->deptUsers
            ]);
        }
    }

    /**
     * Deletes an existing GkyQyhUser model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $qyh = $model->qyh;

        $options = array(
            'token'=>'gky',
            'encodingaeskey'=>$qyh->aeskey,
            'appid'=>$qyh->corpid,
            'appsecret'=>$qyh->secret,
        );
        $weObj = new QyWechat($options);
        $result = $weObj->deleteUser($model->userid);
//        if($result['errcode'] == 0){
            //删除部门
            GkyQyhDeptUser::deleteAll(['user_id'=>$model->userid,'qyh_id'=>$model->qyh_id]);
            //删除成员
            $model->delete();

//        }

        return $this->redirect(['index']);
    }

    /**
     * Finds the GkyQyhUser model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return GkyQyhUser the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = GkyQyhUser::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
